package com.bawei.module_mine.ui.login.view

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.style.ForegroundColorSpan
import android.util.TypedValue
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.appcompat.widget.Toolbar
import androidx.core.os.bundleOf
import androidx.fragment.app.activityViewModels
import androidx.navigation.NavController
import androidx.navigation.Navigation
import com.bawei.lib_common.base.state.Empty
import com.bawei.lib_common.base.state.Failed
import com.bawei.lib_common.base.state.Loading
import com.bawei.lib_common.base.state.Success
import com.bawei.lib_common.flow_eventbus.LoginEvent
import com.bawei.lib_common.flow_eventbus.post.postEvent
import com.bawei.lib_common.observeWithLifecycle
import com.bawei.lib_common.utils.ToastUtils
import com.bawei.module_mine.R
import com.bawei.module_mine.databinding.FragmentSmsCodeBinding
import com.bawei.module_mine.ui.login.LoginActivity
import com.bawei.module_mine.ui.login.LoginViewModel
import com.bawei.myclub.base.mvvm.view.BaseFragment
import com.bawei.myclub.base.mvvm.view.BaseToolbarFragment

class SmsCodeFragment : BaseFragment<LoginViewModel, FragmentSmsCodeBinding>() {


    override val mLayoutResId: Int
        get() = R.layout.fragment_sms_code
    override val mViewModel: LoginViewModel by activityViewModels()

    private lateinit var secSpan: ForegroundColorSpan
    private lateinit var textSpan: ForegroundColorSpan
    private lateinit var mNavController: NavController
    private val mAction by lazy {
        arguments?.getString("action_sms_code") ?: ""
    }
    private val mRestSmsCodeSuccess by lazy {
        arguments?.getBoolean("reset_sms_code_success") ?: false
    }

    private var mCurrentSmsCode: String = ""

    //倒计时
    private val mCountDownHandler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            if (System.currentTimeMillis() - mViewModel.sendSmsCodeTimeStamp > 60_000) {
                onCountDownFinished()
            } else {
                onTick(60 - (System.currentTimeMillis() - mViewModel.sendSmsCodeTimeStamp) / 1000)
            }
        }
    }

    override fun initView() {
        mNavController = Navigation.findNavController(mBinding.root)
        mViewModel.setShowingFragmentTag(SmsCodeFragment::class.simpleName!!)
        val typedValue = TypedValue()
        requireContext().theme.resolveAttribute(
            com.bawei.lib_common.R.attr.colorTheme,
            typedValue,
            true
        )
        secSpan = ForegroundColorSpan(typedValue.data)
        requireContext().theme.resolveAttribute(
            com.bawei.lib_common.R.attr.colorLightText,
            typedValue,
            true
        )
        textSpan = ForegroundColorSpan(typedValue.data)
    }

    override fun initListener() {
        //重新发送验证码
        mBinding.tvResend.setOnClickListener {
            mViewModel.requestRest = false
            mViewModel.sendSmsCode(mAction)
        }

        //发送验证码
        mViewModel.requestSmsCodeEvent.observeWithLifecycle(viewLifecycleOwner) {
            when (it) {
                is Success -> {
                    mBinding.verifyView.showSoftKeyBoard()
                    mViewModel.sendSmsCodeTimeStamp = System.currentTimeMillis()
                    setLoadingViewVisible(false)
                    if (mAction != SmsCode.RESET.type)
                    ToastUtils.showShort(requireContext(), "验证码已发送")
                    showCountDown()
                }

                is Loading -> {
                    setLoadingViewVisible(true)
                }

                is Failed -> {
                    setLoadingViewVisible(false)
                    onCountDownFinished()
                    if (mAction != SmsCode.RESET.type)
                        Toast.makeText(requireContext(), it.message, Toast.LENGTH_SHORT).show()
                }

                else -> {}
            }
        }

        //登录事件
        mViewModel.requestLoginEvent.observeWithLifecycle(viewLifecycleOwner) {
            when (it) {
                is Success -> {
                    setLoadingViewVisible(false)
                    //发送登录成功消息
                    (activity as? LoginActivity)?.handleLoginSuccess()
                    Toast.makeText(requireContext(), "登录成功", Toast.LENGTH_SHORT).show()
                }

                is Loading -> {
                    setLoadingViewVisible(true)
                }

                is Failed -> {
                    setLoadingViewVisible(false)
                    mBinding.verifyView.showSoftKeyBoard()
                    ToastUtils.showShort(requireContext(), it.message)
                }

                else -> {

                }
            }
        }

        mViewModel.mCheckSmsCodeEvent.observeWithLifecycle(viewLifecycleOwner) {
            when (it) {
                is Success -> {
                    setLoadingViewVisible(false)
                    mBinding.verifyView.clear()

                    //重置密码
                    mViewModel.requestRest = true
                    //调整数据新密码页面
                    mNavController.navigate(
                        R.id.action_smsCodeFragment_to_restPsdFragment,
                        bundleOf("action_sms_code" to mCurrentSmsCode)
                    )
                }

                is Loading -> {
                    setLoadingViewVisible(true)
                }

                is Failed -> {
                    setLoadingViewVisible(false)
                    ToastUtils.showShort(context, it.message)
                }

                else ->{

                }
            }
        }

        mBinding.verifyView.setOnInputVerifyCodeCompleted {
            if (mAction == SmsCode.LOGIN.type) {
                //验证码登录
                mViewModel.loginBySmsCode(it)
            } else if (mAction == SmsCode.RESET.type) {
                //校验验证码
                mCurrentSmsCode = it
            }
        }


    }


    override fun initData() {
        mBinding.viewmodel = mViewModel
        if (mViewModel.requestRest) {
            //重置密码页面返回，不自动获取新的验证码
            onCountDownFinished()
        } else {
            if (mAction != SmsCode.RESET.type) {
                mViewModel.sendSmsCode(mAction)
            } else {
                mViewModel.resetSmsCodeEvent(mRestSmsCodeSuccess)
            }
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        mCountDownHandler.removeCallbacksAndMessages(null)
    }

    private fun isOutsideOfView(v: View?, event: MotionEvent): Boolean {
        if (v != null) {
            val leftTop = intArrayOf(0, 0)
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop)
            val left = leftTop[0]
            val top = leftTop[1]
            val bottom = top + v.height
            val right = left + v.width
            return !(event.x > left && event.x < right && event.y > top && event.y < bottom)
        }
        return false
    }

    //重新发送验证码
    private fun onTick(sec: Long) {
        val content = "$sec 秒后重新获取"
        val builder = SpannableStringBuilder(content)
        builder.setSpan(secSpan, 0, content.indexOf("秒"), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        builder.setSpan(
            textSpan,
            content.indexOf("秒"),
            content.length,
            Spannable.SPAN_INCLUSIVE_INCLUSIVE
        )
        mBinding.tvCountDown.text = builder
        mCountDownHandler.sendEmptyMessageDelayed(1, 1_000)
    }

    //倒计时结束
    private fun onCountDownFinished() {
        mBinding.tvResend.visibility = View.VISIBLE
        mBinding.tvCountDown.visibility = View.GONE
    }

    //倒计时显示
    private fun showCountDown() {
        mBinding.tvCountDown.visibility = View.VISIBLE
        mBinding.tvResend.visibility = View.GONE
        mCountDownHandler.sendEmptyMessage(1)
    }


}

enum class SmsCode(val type: String) {
    LOGIN("login"), RESET("rest"), BIND("bind")
}